package cn.xuqiudong.demo.generate.filter;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述: HTTP基本认证(Basic Authentication)
 * @author Vic.xu
 * @since 2023-08-23 10:51
 */
@WebFilter
public class AuthorizationFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("into AuthorizationFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String authz = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (authz == null) {
            response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic");
            response.sendError(HttpStatus.UNAUTHORIZED.value());
            return;
        }
        System.out.println("authz = "  + authz);
        filterChain.doFilter(request, response);
    }
}
